﻿#include <QEventLoop>
#include <QTimer>
#include <QMessageBox>
#include <QUuid>
#include <QCoreApplication>
#include <QDate>
#include <QDir>
#include <QTextStream>
#include <QDebug>
#include "Public.h"

void setWindowsTitleBarColor(HWND hwnd, COLORREF color)
{
	// Win10 1709+ 的属性值
	const DWORD DWMWA_CAPTION_COLOR = 35;
	HRESULT hr = DwmSetWindowAttribute(hwnd, DWMWA_CAPTION_COLOR, &color, sizeof(color));
	return;
}

void sysSleep(int nMsTime)
{
	QEventLoop loop;
	QTimer::singleShot(nMsTime, &loop, SLOT(quit()));
	loop.exec();
}

int messageBox(int nMsgLevel, QString sMsg)
{
	if (nMsgLevel == 0)
	{
		int nRet = QMessageBox::information(nullptr, QString::fromLocal8Bit("信息"), sMsg);
		return nRet;
	}
	else if (nMsgLevel == 1)
	{
		int nRet = QMessageBox::warning(nullptr, QString::fromLocal8Bit("警告"), sMsg);
		return nRet;
	}
	else if (nMsgLevel == 2)
	{
		int nRet = QMessageBox::critical(nullptr, QString::fromLocal8Bit("错误"), sMsg);
		return nRet;
	}
	else if (nMsgLevel == 3)
	{
		int nRet = QMessageBox::question(nullptr, QString::fromLocal8Bit("询问"), sMsg, QMessageBox::Yes | QMessageBox::No | QMessageBox::Close);
		return nRet;
	}

	return 0;
}

QString createGuid()
{
	// 生成一个新的 UUID
	QUuid uuid = QUuid::createUuid();

	// 将生成的 UUID 转换为二进制数据
	QByteArray uuidBytes = uuid.toRfc4122();

	// 将二进制数据转换为十六进制字符串（无连字符）
	QString uuidString;
	for (int i = 0; i < uuidBytes.size(); ++i)
	{
		uuidString += QString("%1").arg((unsigned char)uuidBytes.at(i), 2, 16, QChar('0'));
	}
	return uuidString;
}

void logText(const QString& text) 
{
	// 获取软件安装目录
	QString baseDir = QCoreApplication::applicationDirPath();

	// 获取当前日期并格式化为年月日
	QDate currentDate = QDate::currentDate();
	QString year = QString::number(currentDate.year());
	QString month = QString::number(currentDate.month()).rightJustified(2, '0'); // 补零成两位
	QString day = QString::number(currentDate.day()).rightJustified(2, '0');

	// 构建目标路径：安装目录/Request/年/月/日
	QString logDirPath = baseDir + "/Request/" + year + "/" + month + "/" + day;
	QDir logDir(logDirPath);

	// 递归创建目录（如果不存在）
	if (!logDir.exists()) 
	{
		if (!logDir.mkpath("."))
		{
			qDebug() << "错误：无法创建目录" << logDirPath;
			return;
		}
	}

	// 写入日志文件
	QString logFilePath = logDirPath + "/log.txt";
	QFile file(logFilePath);
	if (file.open(QIODevice::Append | QIODevice::Text)) 
	{
		QTextStream out(&file);
		out.setCodec("UTF-8");
		out << text << "\n"; // 写入文本并换行
		file.close();
	}
	else 
	{
		qDebug() << "错误：无法打开文件" << logFilePath;
	}
}
